import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:hari_curly/src/common/style.dart';
import 'package:hari_curly/src/components/layout.dart';
import 'package:hari_curly/src/config/PermissionConfig.dart';
import 'package:hari_curly/src/model/device_info.dart';
import 'package:hari_curly/src/model/device_model.dart';
import 'package:hari_curly/src/router/router.dart';
import 'package:hari_curly/src/states/device_connect_status.dart';
import 'package:hari_curly/src/states/device_info_state.dart';
import 'package:hari_curly/src/view/home/home.dart';
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:permission_handler/permission_handler.dart';

import 'src/config/init_db.dart';

const localeMap = [
  {"name": "简体中文", "locale": "zh"},
  {"name": "English", "locale": "en"},
  {"name": "Español", "locale": "es"},
  {"name": "Français", "locale": "fr"},
  {"name": "Deutsch", "locale": "de"},
  {"name": "Русский", "locale": "ru"},
  {"name": "العربية", "locale": "ar"},
];

void main() async {
  FlutterBluePlus.setLogLevel(LogLevel.verbose, color: true);
  var locales = localeMap.map((e) => Locale(e['locale']!)).toList();
  WidgetsFlutterBinding.ensureInitialized();
  await InitDb.initialize();
  await EasyLocalization.ensureInitialized();
  runApp(
    EasyLocalization(
      supportedLocales: locales,
      path: 'assets/translations',
      fallbackLocale: const Locale('zh'),
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) => DeviceConnectStatus(
            DeviceModel(id: "-1", name: "未连接", status: "0"),
          ),
        ),
        BlocProvider(
            create: (context) => DeviceInfoStatus(
              DeviceInfo(wind: "low",temperature: "low"),
            ),
        )
      ],
      child: MaterialApp.router(
        localizationsDelegates: context.localizationDelegates,
        supportedLocales: context.supportedLocales,
        locale: context.locale,
        routerConfig: initRouter(),
        theme: ThemeData(
          textTheme: Theme.of(context).textTheme.apply(
            bodyColor: Colors.white,
            displayColor: Colors.white,
          ),
          useMaterial3: true,
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  final ScrollController _scrollController = ScrollController();

  BluetoothAdapterState _adapterState = BluetoothAdapterState.unknown;

  late StreamSubscription<BluetoothAdapterState> _adapterStateStateSubscription;

  @override
  void initState() {
    super.initState();
    _adapterStateStateSubscription = FlutterBluePlus.adapterState.listen((
      state,
    ) {
      _adapterState = state;
      if (mounted) {
        setState(() {});
      }
    });
    checkAndRequestBluetoothScanPermission();
  }

  Future<void> checkAndRequestBluetoothScanPermission() async {
    final status = await Permission.bluetoothScan.status;
    if (status.isGranted) {
      // 已授权，可以开始扫描
    } else {
      final result = await Permission.bluetoothScan.request();
      if (result.isGranted) {
        // 权限已获取，可以开始扫描
      } else {
        // 权限被拒绝，提示用户
      }
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _adapterStateStateSubscription.cancel();
    super.dispose();
  }

  _showLanguagePicker() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          // 上面圆角
          decoration: BoxDecoration(
            color: unitBgColor,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
          ),
          padding: EdgeInsets.symmetric(vertical: 16, horizontal: 0),
          height: 240,
          child: ListView.builder(
            itemCount: localeMap.length,
            controller: _scrollController,
            itemBuilder: (BuildContext context, int index) {
              var foregroundColor = Colors.white;
              var backgroundColor = unitBgColor;
              if (EasyLocalization.of(context)!.currentLocale?.languageCode ==
                  localeMap[index]['locale']!) {
                foregroundColor = Colors.lightBlue;
                _scrollController.animateTo(
                  index * 48.0,
                  duration: Duration(microseconds: 400),
                  curve: Curves.linear,
                );
              }
              return TextButton(
                style: TextButton.styleFrom(
                  foregroundColor: foregroundColor,
                  backgroundColor: backgroundColor,
                ),
                onPressed: () {
                  EasyLocalization.of(
                    context,
                  )!.setLocale(Locale(localeMap[index]['locale']!));
                  Navigator.pop(context);
                },
                child: Text(localeMap[index]['name']!),
              );
            },
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: pageBgColor,
      appBar: AppBarUnit(title: Text(('title').tr())),
      // 更具 底部导航栏的索引值，显示不同的页面
      body: HomePage(),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.language),
        shape: CircleBorder(),
        backgroundColor: unitBgColor,
        foregroundColor: Colors.white,
        elevation: 4.0,
        mini: true,
        onPressed: () {
          _showLanguagePicker();
        },
      ),
    );
  }
}
